import Taro, { Component } from '@tarojs/taro'
import { View, Text, Picker, Image, Input, ScrollView } from '@tarojs/components'
import './Chat.css'
import { AtDivider, AtAvatar, AtList, AtListItem, AtInput, AtForm, AtButton, AtGrid, AtIcon } from "taro-ui"
import app from '../../../../main.js';
import reactMixin from 'react-mixin';
import myJs from './ChatJs.js'
import luyin from '../../../../img/yuyinB.png'
import keyboard from '../../../../img/jianpangB.png'
import plus from '../../../../img/plus.png'
import icon_link from '../../../../img/icon_link.png'
import item_image from '../../../../img/item_image.png'

export default class Chat extends Component {

    config = {
        navigationBarTitleText: '咨询记录'
    }
    constructor() {
        super(...arguments);
        this.state = this.getData();
    }

    init() {
        this.setState({
            is_show_luyin: true,
            is_open_grid: false,
            current_index: 0,
            wenzen_order: {},
            flow_order: {},
            statuses: ['咨询结束', '已评价', '待退款', '已退款', '退款失败', '随访结束']
        })
        this.initData();
        this.getMessages();
        this.onEndedAudio();
        this.setNavigationTitle();
        this.getOrder();
        this.getFlowOrder();
    }

    componentDidShow() {
        this.sendArticle();
        this.sendFlow();
    }

    getOrder() {
        var me = this;
        if (me.state.type == '问诊订单') {
            app.get('web/wenzen_order/order', { id: me.state.relate_id }, function (res) {
                me.setState({
                    wenzen_order: res.data.result
                }, () => {
                    me.showRemainTime();
                })
            })
        }
    }

    getFlowOrder() {
        let me = this
        if (me.state.type == '随访') {
            app.get('web/flow_order/get', { id: me.state.relate_id }, function (res) {
                me.setState({
                    flow_order: res.data.result
                }, () => {
                    me.showRemainTime();
                })
            })
        }
    }

    setNavigationTitle() {
        var me = this;
        app.get('web/patient/get', { id: this.state.receiver_id }, function (res) {
            Taro.setNavigationBarTitle({ title: res.data.result.name + '的咨询记录' });
        })
    }

    offset = 0;
    length = 10;
    total = 0;

    // 初始化参数
    initData() {
        this.setState({
            mySelfId: 'd-' + this.state.sender_id,
            otherId: 'p-' + this.state.receiver_id
        }, () => {
            this.initSocket();
        })
    }

    changeLuYin(v) {
        this.setState({ is_show_luyin: v })
    }

    clickFavour() {

    }
    openGrid() {
        this.setState({
            is_open_grid: !this.state.is_open_grid
        }, () => {
            this.toPageBottoms()
        })
    }

    toPageBottoms() {
        let me = this
        if (this.state.is_open_grid == true) {
            var query1 = Taro.createSelectorQuery()
            query1.select('.bottom').boundingClientRect()
            query1.selectViewport().scrollOffset()
            query1.exec(function (res) {
                me.setState({
                    height: res[0].height + 200
                }, () => {
                    var query2 = Taro.createSelectorQuery()
                    query2.select('#page_v').boundingClientRect()
                    query2.selectViewport().scrollOffset()
                    query2.exec(function (ress) {
                        let marT = res[0].height + ress[0].height
                        Taro.pageScrollTo({
                            scrollTop: marT,
                            duration: 300
                        })
                    })
                })
            })
        }
    }

    // 查看图片大图
    showImage(image) {
        app.prviewImage(image, [image]);
    }

    innerAudioContext = Taro.createInnerAudioContext();

    // 音频播放结束监听事件
    onEndedAudio() {
        var me = this;
        this.innerAudioContext.onEnded(function (res) {
            console.log('播放结束', res);
            var messages = me.state.messages;
            messages[me.state.current_index].is_play = false;
            me.setState({
                messages: messages
            })
        })
    }

    // 点击音频
    clickAudio(url, index) {
        var messages = this.state.messages;
        var is_play = !messages[index].is_play;
        console.log(url, index);
        console.log(messages);
        for (var i = 0; i < messages.length; i++) {
            if (i == index) {
                messages[index].is_play = is_play;
            } else {
                messages[i].is_play = false;
            }
        }
        this.setState({
            messages: messages,
            current_index: index
        })

        this.innerAudioContext.src = url;
        if (is_play) {
            this.innerAudioContext.play();
        } else {
            this.innerAudioContext.stop();
        }
    }

    // 下拉刷新
    onPullDownRefresh() {
        if (this.offset < this.total) {
            this.offset += this.length;
            this.getMessages();
        } else {
            Taro.stopPullDownRefresh();
            app.toastMessage('没有消息了');
        }
    }

    // 发送患教
    sendArticle() {
        var me = this;
        var list = app.ct_articles;
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            var data = {
                id: item.id,
                title: item.title
            }
            this.setState({
                data: JSON.stringify(data)
            }, () => {
                this.send('article');
            });
        }
        app.ct_articles = [];
    }

    changeGrid(item, index) {
        var me = this;
        if (index == 0) {
            this.uploadImage();
        } else if (index == 1) {
            this.uploadVideo();
        } else if (index == 2) {
            app.ct_articles = [];
            app.navigateTo('../../../doctorpages/aiyanPolular/aiyanPolular');
        } else if (index == 3) {
            app.ct_flow = {};
            app.get('web/flow_plan/is_has_plan', { patient_id: me.state.receiver_id }, function (res) {
                var result = res.data.result;
                if (result.is_has) {
                    var flow_plan = result.flow_plan;
                    app.ct_flow = {
                        id: flow_plan.id,
                        title: flow_plan.title
                    }
                    me.sendFlow();
                } else {
                    app.navigateTo('../../../flow/pages/suifangjihua/suifangjihua?patient_id=' + me.state.receiver_id + '&from_page=chat');
                }
            })
        }
    }

    // 发送随访
    sendFlow() {
        var me = this;
        var flow = app.ct_flow;
        if (flow.id && flow.title) {
            var type = '';
            var relate_id = '';
            if (!app.isEmpty(me.state.wenzen_order.id)) {
                type = '问诊订单';
                relate_id = me.state.wenzen_order.id;
            }
            if (!app.isEmpty(me.state.flow_order.id)) {
                type = '随访';
                relate_id = me.state.flow_order.id;
            }
            if (!app.isEmpty(relate_id)) {
                me.setState({
                    type: type,
                    relate_id: relate_id,
                    data: JSON.stringify(flow)
                }, () => {
                    var task = me.state.socketTask;
                    if (task.readyState == 1) {
                        me.send('flow');
                    } else {
                        me.state.socketTask.onOpen(function () {
                            me.send('flow');
                        })
                    }
                    app.ct_flow = {};
                })
            }
        }
    }

    // 结束问诊会话
    endSession() {
        var me = this;
        app.isConfirm('是否结束会话', function (res) {
            app.post('web/wenzen_order/close_zixun', { id: me.state.relate_id }, function (res) {
                if (res.data.status == 200) {
                    var data = {
                        title: '本次咨询结束',
                        time: app.dateFormate(new Date(), "yyyy-MM-dd hh:mm:ss")
                    }
                    var wenzen_order = me.state.wenzen_order;
                    wenzen_order.status = '咨询结束';
                    me.setState({
                        data: JSON.stringify(data),
                        wenzen_order: wenzen_order
                    }, () => {
                        me.send('flag');
                    })
                } else {
                    app.toastMessage('结束会话失败');
                }
            })
        })
    }

    // 结束随访会话
    endFlowSession() {
        var me = this;
        app.isConfirm('是否结束会话', function (res) {
            app.post('web/flow_order/toFinish', { id: me.state.relate_id }, function (res) {
                if (res.data.status == 200) {
                    var data = {
                        title: '本次随访结束',
                        time: app.dateFormate(new Date(), "yyyy-MM-dd hh:mm:ss")
                    }
                    var flow_order = me.state.flow_order;
                    flow_order.status = '随访结束';
                    me.setState({
                        data: JSON.stringify(data),
                        flow_order: flow_order
                    }, () => {
                        me.send('flag');
                    })
                } else {
                    app.toastMessage('结束会话失败');
                }
            })
        })
    }

    closeTop() {
        this.setState({
            is_show_top: false
        })
    }

    getRemainTime(endTime) {
        var endDate = new Date(endTime);
        var nowDate = new Date();
        var interval = endDate.getTime() - nowDate.getTime();
        interval = Math.abs(interval);
        interval = interval / 1000;
        var total = 24 * 60 * 60;
        var remain = total - interval;

        var hour = remain / 60 / 60;
        var minute = remain % (60 * 60) / 60;
        hour = Math.floor(hour);
        minute = Math.floor(minute);
        minute = minute > 0 ? minute : 1;

        var str = '还剩余';
        if (hour > 0) {
            str += hour + '小时';
        }
        if (minute > 0) {
            str += minute + '分钟';
        }

        return str;
    }

    showRemainTime() {
        var wenzen_order = this.state.wenzen_order;
        var flow_order = this.state.flow_order;
        var endTime = '';
        var status = '';
        if (!app.isEmpty(wenzen_order.id)) {
            endTime = !app.isEmpty(wenzen_order.pay_time) ? wenzen_order.pay_time : wenzen_order.created_at;
            status = wenzen_order.status;
        } else if (!app.isEmpty(flow_order.id)) {
            endTime = flow_order.created_at;
            status = flow_order.status;
        }

        var arr = ['待随访', '随访中', '已支付', '待回复', '咨询中'];
        if (!app.isEmpty(endTime) && !app.isEmpty(status) && app.inArray(arr, status)) {
            var top_desc = this.getRemainTime(endTime);
            var is_show_top = top_desc == '还剩余1分钟' ? false : true;
            this.setState({
                is_show_top: is_show_top,
                top_desc: top_desc
            })
        }
    }

    onFormSubmit(e) {
        console.log(e);
        this.setState({
            form_id: e.detail.formId
        }, () => {
            this.send('text');
        })
    }

    render() {
        let styles = this.state.is_open_grid == true ? `width:750rpx;height:${this.state.height}rpx` : 'width:750rpx;height:200rpx'
        return (
            <View id='page_v'>
                <View className={this.state.is_show_top ? 'top' : 'hide'}>
                    <View className='tp_text'>{this.state.top_desc}</View>
                    <AtIcon className='tp_icon' value='close-circle' size='30' color='#fff' onClick={this.closeTop.bind(this)}></AtIcon>
                </View>
                <View className={this.state.is_show_top ? 'top_blank' : 'hide'}></View>
                {
                    this.state.messages.map((item, index) => {
                        if (item.type == 'text' && !item.isMyself) {
                            return (
                                <View className='chat_item'>
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <View className='content_txt'>{item.data}</View>
                                </View>
                            )
                        } else if (item.type == 'text' && item.isMyself) {
                            return (
                                <View className='chat_item right'>
                                    <View className='content_txt'>{item.data}</View>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'image' && !item.isMyself) {
                            return (
                                <View className='chat_item'>
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <Image className='content_image' mode='widthFix' src={app.getPath(item.data)} onClick={this.showImage.bind(this, item.data)}></Image>
                                </View>
                            )
                        } else if (item.type == 'image' && item.isMyself) {
                            return (
                                <View className='chat_item right'>
                                    <Image className='content_image' mode='widthFix' src={app.getPath(item.data)} onClick={this.showImage.bind(this, item.data)}></Image>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'video' && !item.isMyself) {
                            return (
                                <View className='chat_item'>
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <Video
                                        src={app.getPath(item.data)}
                                        controls={true}
                                        autoplay={false}
                                        initialTime='0'
                                        id='video'
                                        loop={false}
                                        muted={false}
                                        className='content_video'
                                    />
                                </View>
                            )
                        } else if (item.type == 'video' && item.isMyself) {
                            return (
                                <View className='chat_item right'>
                                    <Video
                                        src={app.getPath(item.data)}
                                        controls={true}
                                        autoplay={false}
                                        initialTime='0'
                                        id='video'
                                        loop={false}
                                        muted={false}
                                        className='content_video'
                                    />
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'audio' && !item.isMyself) {
                            return (
                                <View className='chat_item'>
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <View className='audio_box'>
                                        <Image className='audio_image' src={app.getPath('img/play_left.png')}></Image>
                                        <View className='audio_txt'>{item.data.time}''</View>
                                    </View>
                                </View>
                            )
                        } else if (item.type == 'audio' && item.isMyself) {
                            return (
                                <View className='chat_item right'>
                                    <View className='audio_box' onClick={this.clickAudio.bind(this, item.data.url, index)}>
                                        <View className='audio_txt'>{item.data.time}''</View>
                                        <Image className='audio_image' src={item.is_play ? app.getPath('img/play_right.gif') : app.getPath('img/play_right.png')}></Image>
                                    </View>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'article' && !item.isMyself) {
                            return (
                                <View className='chat_item'>
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <View className='article' >
                                        <Image className='icon_link' src={icon_link}>/</Image>
                                        <View className='article_txt'>{item.data.title}</View>
                                    </View>
                                </View>
                            )
                        } else if (item.type == 'article' && item.isMyself) {
                            return (
                                <View className='chat_item right'>
                                    <View className='article' >
                                        <Image className='icon_link' src={icon_link}>/</Image>
                                        <View className='article_txt'>{item.data.title}</View>
                                    </View>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'flow' && !item.isMyself) {
                            return (
                                <View className="chat_item">
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <View className='flow' onClick={this.navigateTo.bind(this, '../../../flow/pages/suifangjihuaxiangqing/suifangjihuaxiangqing?id=' + item.data.id)}>
                                        <View className='flw_top'>{item.data.title}</View>
                                        <View className='flw_center'>
                                            <Image className='flw_image' src={app.getPath('img/item_image.png')}></Image>
                                            <View className='flw_txt'>我给您定制了一个随访计划，请遵照计划中提醒的内容来执行。</View>
                                        </View>
                                        <View className='flw_desc'>查看详情></View>
                                    </View>
                                </View>
                            )
                        } else if (item.type == 'flow' && item.isMyself) {
                            return (
                                <View className="chat_item right">
                                    <View className='flow' onClick={this.navigateTo.bind(this, '../../../flow/pages/suifangjihuaxiangqing/suifangjihuaxiangqing?id=' + item.data.id)}>
                                        <View className='flw_top'>{item.data.title}</View>
                                        <View className='flw_center'>
                                            <Image className='flw_image' src={app.getPath('img/item_image.png')}></Image>
                                            <View className='flw_txt'>我给您定制了一个随访计划，请遵照计划中提醒的内容来执行。</View>
                                        </View>
                                        <View className='flw_desc'>查看详情></View>
                                    </View>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        } else if (item.type == 'flag') {
                            return (
                                <View className='flag'>
                                    {
                                        !app.isEmpty(item.data.title) &&
                                        <View className='flag_top'>
                                            <View className='dot'>
                                                <View className='fl_dot dot_width'></View>
                                            </View>
                                            <View className='fl_txt'>{item.data.title}</View>
                                            <View className='dot'>
                                                <View className='fr_dot dot_width'></View>
                                            </View>
                                        </View>
                                    }
                                    <View className='f_time'>{item.data.time}</View>
                                </View>
                            )
                        } else if (item.type == 'wz_illness_form' && !item.isMyself) {
                            return (
                                <View className="chat_item">
                                    <Image className='head_image' src={app.getPath(item.receiver_head_image)} onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}></Image>
                                    <View className='flow' onClick={this.navigateTo.bind(this, '../../../doctorpages/Illness/Illness?id=' + item.data.id)}>
                                        <View className='flw_top'>病情表单</View>
                                        <View className='flw_center'>
                                            <Image className='flw_image' src={item_image}></Image>
                                            <View className='flw_txt'>{item.data.title}</View>
                                        </View>
                                        <View className='flw_desc'>查看详情></View>
                                    </View>
                                </View>
                            )
                        } else if (item.type == 'wz_illness_form' && item.isMyself) {
                            return (
                                <View className="chat_item right">
                                    <View className='flow' onClick={this.navigateTo.bind(this, '../../../doctorpages/Illness/Illness?id=' + item.data.id)}>
                                        <View className='flw_top'>病情表单</View>
                                        <View className='flw_center'>
                                            <Image className='flw_image' src={item_image}></Image>
                                            <View className='flw_txt'>{item.data.title}</View>
                                        </View>
                                        <View className='flw_desc'>查看详情></View>
                                    </View>
                                    <Image className='head_image' src={app.getPath(item.sender_head_image)}></Image>
                                </View>
                            )
                        }
                    })
                }

                <View style={styles}></View>

                {
                    (!app.inArray(this.state.statuses, this.state.wenzen_order.status) && !app.inArray(this.state.statuses, this.state.flow_order.status)) ?
                        (
                            <View className='bottom'>
                                <View className='opt'>
                                    <View className='opt1' onClick={this.navigateTo.bind(this, '../../../flow/pages/patientdetails/patientdetails?id=' + this.state.receiver_id)}>查看病历</View>
                                    {
                                        (this.state.type == '问诊订单' && this.state.wenzen_order.status == '咨询中')
                                        &&
                                        <View className='opt2' onClick={this.endSession.bind(this)}>结束会话</View>
                                    }
                                    {
                                        (this.state.type == '随访' && (this.state.flow_order.status == '待随访' || this.state.flow_order.status == '随访中'))
                                        &&
                                        <View className='opt2' onClick={this.endFlowSession.bind(this)}>结束会话</View>
                                    }
                                </View>
                                <View className='send_box'>
                                    {
                                        this.state.is_show_luyin ?
                                            (
                                                <Image src={luyin} className='luyin' onClick={this.changeLuYin.bind(this, false)}></Image>
                                            ) :
                                            (
                                                <Image src={keyboard} className='luyin' onClick={this.changeLuYin.bind(this, true)}></Image>
                                            )
                                    }
                                    {
                                        this.state.is_show_luyin ?
                                            (
                                                <AtInput className='content' value={this.state.value} cursorSpacing={18} border={false} onFocus={this.toPageBottom.bind(this)} onChange={this.handleChange.bind(this)}></AtInput>
                                            ) :
                                            (
                                                <Button className='btn_luyin' type='primary' onTouchStart={this.onTouchStart.bind(this)} onTouchEnd={this.onTouchEnd.bind(this)}>按住说话</Button>
                                            )
                                    }
                                    {
                                        this.state.value != '' ?
                                            (
                                                <AtForm className='form' reportSubmit={true} onSubmit={this.onFormSubmit.bind(this)}>
                                                    <AtButton formType='submit' className='send_btn' type='primary' size='small'>发送</AtButton>
                                                </AtForm>
                                            ) :
                                            (
                                                <Image src={plus} className='icon_plus' onClick={this.openGrid.bind(this)}></Image>
                                            )
                                    }
                                </View>
                                <View className={this.state.is_open_grid ? 'closeBox' : 'hide'}>
                                    <AtGrid onClick={this.changeGrid.bind(this)} columnNum={4} data={
                                        [
                                            {
                                                image: app.getPath('img/tupianB.png'),
                                                value: '相册'
                                            },
                                            {
                                                image: app.getPath('img/xiangjiB.png'),
                                                value: '视频'
                                            },
                                            {
                                                image: app.getPath('img/huanjiao.png'),
                                                value: '患教'
                                            },
                                            {
                                                image: app.getPath('img/suifang.png'),
                                                value: '随访'
                                            }
                                        ]
                                    } />
                                </View>
                            </View>
                        ) : (
                            null
                        )
                }
            </View>
        )
    }
}
reactMixin.onClass(Chat, myJs);
